﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Resources;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;
using Common;
using DevExpress.XtraEditors;
using System.ComponentModel;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Model;
using PositionServer.Service;
using PlatformClient.Service;
using PlatformClient.Properties;

namespace PlatformClient
{
    public partial class MainForm : XtraForm
    {


        public static IPositionService PositionService;
        readonly System.Windows.Forms.Timer _timerPerf = new System.Windows.Forms.Timer();
        private static readonly Hashtable DeviceList = Hashtable.Synchronized(new Hashtable());
        // 87private static readonly Dictionary<string,TaxiInfo> TaxiList=new Dictionary<string, TaxiInfo>();

        //public static string UserName = string.Empty;
        //public static string UserPermission = string.Empty;

        private GMapOverlay _taxis;
        private bool _isPartRefresh;
        public static bool IsLoginOk;


        private readonly BackgroundWorker _backgroundWorker;

        private readonly DataTable _dtDeviceList = new DataTable();
        private DataRow _drCurrentClickTaxiInfo;

        private DataTable _gridDataTable = new DataTable();

        readonly System.Media.SoundPlayer _player = new System.Media.SoundPlayer(Resources.waring);
        readonly System.Media.SoundPlayer _playersms = new System.Media.SoundPlayer(Resources.sms_received1);
        private bool _isAlarmSound = true;

        private GMapOverlay _overlay;
        private GMapOverlay _overlaySearch;
       
        public static double ClientVersion = 1.06;

        public static MainForm MainForm1;

        private int _userDropLineTime=300;//单位为s


        public static UserInfo MyUserInfo;

        public MainForm()
        {
            InitializeComponent();

         

            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.DoWork += worker_DoWork;
            _backgroundWorker.RunWorkerAsync();
            LoginForm frm = new LoginForm(this._backgroundWorker);
            frm.ShowDialog();
            //MainMap.t
        }

        private void Init()
        {
        
            // _dtTaxiList
            _dtDeviceList.Columns.Add("Emi");
            _dtDeviceList.Columns.Add("手机号码");
            _dtDeviceList.Columns.Add("在线状态");
            _dtDeviceList.Columns.Add("经度");
            _dtDeviceList.Columns.Add("纬度");
            _dtDeviceList.Columns.Add("数据更新时间");
            _dtDeviceList.Columns.Add("IP地址");
           //_dtTaxiList.Columns.Add("出租车ID");

            this.Text = "校车监控管理系统平台 V" + ClientVersion.ToString("f");

            //Map
            double theCenterLat = Settings.Default.MainMapLat;
            double theCenterLng = Settings.Default.MainMapLng;

            MainMap.Manager.Mode = AccessMode.ServerAndCache;
            MainMap.MapProvider = GMapProviders.GoogleChinaMap;

            //  MainMap.MapProvider = GMapProviders.OpenStreetMap;
            _overlay = new GMapOverlay("Overlay");
            MainMap.Overlays.Add(_overlay);
            _overlaySearch = new GMapOverlay("Select");
            MainMap.Overlays.Add(_overlaySearch);

            _taxis = new GMapOverlay("Taxi");
            MainMap.Overlays.Add(_taxis);
            MainMap.MaxZoom = 18;
            MainMap.MinZoom = 10;

            MainMap.Zoom = 12;
            MainMap.Position = new PointLatLng(theCenterLat, theCenterLng);
            MainMap.DragButton = MouseButtons.Left;

            // trackBarControl_MapZoom
            trackBarControl_MapZoom.Properties.Minimum = MainMap.MinZoom;
            trackBarControl_MapZoom.Properties.Maximum = MainMap.MaxZoom;
            trackBarControl_MapZoom.Value = (int)MainMap.Zoom;

            repositoryItemCheckEdit1.CheckedChanged += new EventHandler(repositoryItemCheckEdit1_CheckedChanged);
                  
            // GetTaxiInThread
            Thread t = new Thread(GetTaxisInThread) { IsBackground = true };
            t.Start();

            //Thread thread = new Thread(GetOverlayInThread) { IsBackground = true };
            //thread.Start();         
            MainForm1 = this;


            SetMenuItemsEnableByPermission();
        }
 
         
        /// <summary> 
        /// worker start 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!IsLoginOk)
            {
                Thread.Sleep(500);
                //Application.DoEvents();
            }
            Init();
        }

        public static bool InitWcfService(string ip)
        {
            try
            {
                NetTcpBinding netbinding = new NetTcpBinding(SecurityMode.None, true)
                {
                    MaxBufferPoolSize = 2147483647,
                    MaxBufferSize = 2147483647,
                    MaxReceivedMessageSize = 2147483647,
                    SendTimeout = new TimeSpan(0, 10, 18),
                    ReceiveTimeout = new TimeSpan(0, 10, 18),
                    ReliableSession = { Enabled = true, InactivityTimeout = new TimeSpan(0, 5, 0) },
                    ReaderQuotas =
                    {
                        MaxArrayLength = 2147483647,
                        MaxStringContentLength = 2147483647,
                        MaxBytesPerRead = 2147483647
                    },
                    TransferMode = TransferMode.Buffered,
                };
                netbinding.MaxConnections = 65536000;
                ChannelFactory<IPositionService> factory = new ChannelFactory<IPositionService>
                                     (netbinding, new EndpointAddress("net.tcp://" + ip + ":" + ConstParameters.WcfPort + "/PositionServices"));
                foreach (System.ServiceModel.Description.OperationDescription op in factory.Endpoint.Contract.Operations)
                {
                    System.ServiceModel.Description.DataContractSerializerOperationBehavior dataContractBehavior =
                                op.Behaviors.Find<System.ServiceModel.Description.DataContractSerializerOperationBehavior>();
                    if (dataContractBehavior != null)
                    {
                        dataContractBehavior.MaxItemsInObjectGraph = 2147483647;
                    }
                }
                PositionService = factory.CreateChannel();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                return false;
            }
            return true;

        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            //_timerPerf
            _timerPerf.Tick += DrwaTaxiOnMap;
            _timerPerf.Enabled = true;
            _timerPerf.Interval = 1;
            _timerPerf.Start();
            //if (UserName.ToLower() == "changyun")
            //{
            //    barDockControlTop.Enabled = false;
            //}           
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (XtraMessageBox.Show("确定退出平台？", "警告", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                e.Cancel = true;
                return;
            }
            _timerPerf.Interval = 1000000;
            _timerPerf.Stop();

            Properties.Settings.Default.MainMapLat = MainMap.Position.Lat;
            Properties.Settings.Default.MainMapLng = MainMap.Position.Lng;
            Properties.Settings.Default.Save();
            Environment.Exit(0);
        }

        private void trackBarControl_MapZoom_Properties_ValueChanged(object sender, EventArgs e)
        {
            MainMap.Zoom = (trackBarControl_MapZoom.Value);
        }

        private void MainMap_OnMapZoomChanged()
        {
            trackBarControl_MapZoom.Value = (int)(MainMap.Zoom);
            if (_isPartRefresh)
            {
                Console.Write("sss");
                //  GetTaxis(true);
            }
        }

        //private double a1, a2, b1, b2;
        //private int aa = 0;
        private void MainMap_MouseClick(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Left) return;                
             
            //Bitmap obj = Resources.people1_20;
            //switch (markerimg)
            //{
            //    case 0:
            //        break;
            //    case 1:
            //        obj = Resources.people1_30;
            //        break;
            //    case 2:
            //        obj = Resources.people1_40;
            //        break;
            //    case 3:
            //        obj = Resources.people2_20;
            //        break;
            //    case 4:
            //        obj = Resources.people2_30;
            //        break;
            //    case 5:
            //        obj = Resources.people2_40;
            //        break;                
            //}
            //PointLatLng point = MainMap.FromLocalToLatLng(e.X, e.Y);
            //GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
            //{
            //    ToolTipText = markerimg.ToString(),                   
            //    ToolTipMode = MarkerTooltipMode.OnMouseOver
                
            //};        
            //_overlaySearch.Markers.Add(gMarker);
            //markerimg++;
            //if (markerimg == 6) markerimg = 0;
        }

        private int markerimg = 0;


        private void DrwaTaxiOnMap(object sender, EventArgs e)
        {
            DeviceInfo temp = new DeviceInfo();
            lock (DeviceList.SyncRoot)
            {
                foreach (DeviceInfo device in DeviceList.Values)
                {
                    temp = device;
                    break;
                }

                if (temp != null && temp.PhoneNumber != null)
                {
                    lock (_taxis.Markers)
                    {
                        lock (DeviceList.SyncRoot)
                        {
                            DeviceList.Remove(temp.PhoneNumber);
                        }
                        GMapMarker g =
                            _taxis.Markers.FirstOrDefault(
                                gMapMarker => gMapMarker.Tag.ToString() == temp.PhoneNumber);
                        if (g != null)
                        {
                            this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Remove(g)));
                        }

                        string isOline = "在线";
                        Bitmap obj = GetTaxiBitmap(
                            int.Parse(Math.Floor(temp.Angle).ToString()));

                        bool isExistInDt = true;
                        if (_dtDeviceList.Rows.Count > 0)
                        {
                            DataTable dt = _dtDeviceList.Copy();
                            DataRow[] rows = dt.Select("手机号码='" + temp.PhoneNumber + "'");
                            if (rows.Length == 0)
                            {
                                isExistInDt = false;
                            }
                        }

                        TimeSpan timeSpan = new TimeSpan(DateTime.Now.Ticks -
                          temp.UpdateTime.Ticks);
                        if (timeSpan.TotalSeconds > _userDropLineTime
                            || !isExistInDt)
                        {
                            isOline = "下线";

                        }

                        PointLatLng point = new PointLatLng(temp.Lat, temp.Lng);

                        UserMarker gMarker = new UserMarker(point, obj, temp.UpdateTime.ToString("mm:ss"))
                            // GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
                            {
                                ToolTipText =
                                    "车辆牌照：" + temp.Emi + Environment.NewLine                                    
                                    + "手机号码：" + temp.PhoneNumber + Environment.NewLine
                                    + "在线状态：" + isOline + Environment.NewLine                                    
                                    + "更新时间：" + temp.UpdateTime.ToString("HH:mm:ss") +
                                    Environment.NewLine,
                                ToolTipMode = MarkerTooltipMode.OnMouseOver,
                                Tag = temp.PhoneNumber
                            };
                        gMarker.ToolTip.Format.Alignment = StringAlignment.Near;
                        this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Add(gMarker)));
                    }

                }
            }


        }
         
        public static Bitmap GetTaxiBitmap( 
         int angle )
        {
            int value = 9;   
            if ((angle >= 0 && angle <= 20) || (angle >= 340 && angle <= 360))
            {
                value = 1;
            }
            else if (angle > 20 && angle < 70)
            {
                value = 2;
            }
            else if (angle >= 70 && angle <= 110)
            {
                value = 3;
            }
            else if (angle > 110 && angle < 160)
            {
                value = 4;
            }
            else if (angle >= 160 && angle <= 200)
            {
                value = 5;
            }
            else if (angle > 200 && angle < 250)
            {
                value = 6;
            }
            else if (angle >= 250 && angle <= 290)
            {
                value = 7;
            }
            else if (angle > 290 && angle < 340)
            {
                value = 8;
            }
            else
            {
                value = 9;
            }

            string name = "_0" + value.ToString();
            Bitmap obj = (Bitmap)Resources.ResourceManager.GetObject(name);
            if (obj == null)
            {
                Console.WriteLine("？？？？？？？？？");
                obj = Resources._09;
            }
            return obj;
        }

        private bool isFirstGet = true;
        private void GetTaxisInThread()
        {
            //Thread.Sleep(10000);
            while (true)
            {
                if (DeviceList.Count == 0)
                {
                    GetTaxis(isFirstGet);
                }
                Thread.Sleep(100);
                isFirstGet = false;
            }
        }



        private void GetTaxis(bool binding = false)
        {
            try
            {
                List<DeviceInfo> list = PositionService.GetAllDeviceLocation();
              
                lock (DeviceList.SyncRoot)
                {
                    DeviceList.Clear();
                    _dtDeviceList.Clear();

                    //DeviceInfo nedevice = new DeviceInfo();
                    //nedevice.PhoneNumber = "11111";
                    //nedevice.Lng = 113.962300 ;
                    //nedevice.Lat = 22.547890;
                    //DeviceList[nedevice.PhoneNumber] = nedevice;

                    //DataRow row2 = _dtDeviceList.NewRow();
                    ////double newLat2 = 0;
                    ////double newLng2 = 0;
                    ////GpsTrans.transform(nedevice.Lat, nedevice.Lng,
                    ////    out newLat2, out newLng2);
                    ////nedevice.Lat = newLat2;
                    ////nedevice.Lng = newLng2;

                    //row2["Emi"] = nedevice.Emi;
                    //row2["手机号码"] = nedevice.PhoneNumber;
                    //row2["在线状态"] = nedevice.State;

                    //row2["经度"] = nedevice.Lng;
                    //row2["纬度"] = nedevice.Lat;
                    //row2["数据更新时间"] = nedevice.UpdateTime;
                    //row2["IP地址"] = nedevice.IpAddress;
                    //_dtDeviceList.Rows.Add(row2);


                    foreach (DeviceInfo device in list)
                    {
                        DeviceList[device.PhoneNumber] = device;
                        DataRow row = _dtDeviceList.NewRow();
                        double newLat = 0;
                        double newLng = 0;
                        GpsTrans.transform(device.Lat, device.Lng,
                            out newLat, out newLng);
                        device.Lat = newLat;
                        device.Lng = newLng;

                        row["Emi"] = device.Emi;
                        row["手机号码"] = device.PhoneNumber;
                        row["在线状态"] = device.State;
                         
                        row["经度"] = device.Lng;
                        row["纬度"] = device.Lat;
                        row["数据更新时间"] = device.UpdateTime;
                        row["IP地址"] = device.IpAddress;
                        _dtDeviceList.Rows.Add(row);
                    }

                    List<GMapMarker> delTaxiMarkers = new List<GMapMarker>();
                    foreach (GMapMarker gMapMarker in _taxis.Markers)
                    {
                        if (!DeviceList.Contains(gMapMarker.Tag.ToString()))
                        {
                            delTaxiMarkers.Add(gMapMarker);
                        }
                    }

                    if (delTaxiMarkers.Count > 0)
                    {
                        foreach (GMapMarker gMapMarker in delTaxiMarkers)
                        {
                            GMapMarker marker = gMapMarker;
                            this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Remove(marker)));
                        }
                        delTaxiMarkers.Clear();

                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
           
            
            if (binding)
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    _gridDataTable.Clear();
                    _gridDataTable = _dtDeviceList.Copy();
                    gridControl_TaxiList.DataSource = _gridDataTable;
                    searchLookUpEdit1.Properties.DataSource = _gridDataTable;
                    gridView1.GroupPanelText = "当前一共" + _gridDataTable.Rows.Count + "位员工.";
                    _taxis.Markers.Clear();

                    //gridcontrolTaxiList
                    gridView1.Columns[0].Width = 60;
                    gridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    gridView1.Columns[1].Width = 88;
                    gridView1.Columns[1].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    gridView1.Columns[1].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    gridView1.Columns[2].Width = 108;
                }));

            }
            else
            {
                if (barEditItem_refreshTime.EditValue == null)
                {
                    barEditItem_refreshTime.EditValue = 30;
                }
                int refreshtime;
                int.TryParse(barEditItem_refreshTime.EditValue.ToString(), out refreshtime);
                if (refreshtime < 5)
                {
                    refreshtime = 5;
                }
                Thread.Sleep(refreshtime * 1000);
            }
                  
        }


        

        private void barButtonItem_Topbardriverinfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
        }

        private void barButtonItem_TopbaruserInfo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
         
            UserForm u = new UserForm();
            u.ShowDialog();
        }
 
 

        private void simpleButton_goto_Click(object sender, EventArgs e)
        {
            _overlaySearch.Markers.Clear();
            if (textBoxGeo.Text.Trim() == "")
            {
                //XtraMessageBox.Show("请输入想要查找的地址！");               
                textBoxGeo.Focus();
                return;
            }
            //MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
         
            int count = 0;
            foreach (DataRow dr in DtOverlayList.Rows)
            {
                string markerName = dr["OverlayName"].ToString();
                if (markerName.Contains(textBoxGeo.Text.Trim()))
                {
                    Bitmap obj = GmapOverlayManagementForm.GetMarkerBitmap(dr["Overlaytype"].ToString());
                    PointLatLng point = new PointLatLng(double.Parse(dr["Latitude"].ToString()),
                        double.Parse(dr["Longitude"].ToString()));
                    GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
                    {
                        ToolTipText = dr["OverlayName"].ToString(),
                        ToolTipMode = MarkerTooltipMode.Always
                    };
                    _overlaySearch.Markers.Add(gMarker);
                    count++;
                    if (count == 1)
                    {
                        MainMap.Position = point;
                    }
                }
            }
            if (count == 0)
            {
                MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
            }            
        }

        private void textBoxGeo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                if (textBoxGeo.Text.Trim() == "")
                {
                    XtraMessageBox.Show("请输入想要查找的地址！");
                    textBoxGeo.Focus();
                    return;
                }
                MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
            }

        }
        private void MainMapSetCurrentPositionByKeywords(string positionName)
        {
            GeoCoderStatusCode status = MainMap.SetPositionByKeywords(positionName);
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
            {
                MessageBox.Show("谷歌地图找不到: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                if (_isPartRefresh)
                {
                    lock (DeviceList.SyncRoot)
                    {
                        DeviceList.Clear();
                    }
                    lock (_taxis.Markers)
                    {
                        _taxis.Markers.Clear();
                    }
                    GetTaxis();
                }
            }
        }

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            DataRow dr = searchLookUpEdit1.Properties.View.GetFocusedDataRow();
            if (dr == null) return;
            gridControl_TaxiList.DataSource = dr;
            PointLatLng p = new PointLatLng(double.Parse(dr["纬度"].ToString()), double.Parse(dr["经度"].ToString()));
            MainMap.Position = p;
        }

        private void radioGroup1_EditValueChanged(object sender, EventArgs e)
        {
            if (radioGroup1.SelectedIndex == 0)
            {
                _isPartRefresh = false;
            }
            else if (radioGroup1.SelectedIndex == 1)
            {
                _isPartRefresh = true;
            }
            //GetTaxis(true);
        }

        //
        private void simpleButton_RefreshGridview_Click(object sender, EventArgs e)
        {
            //Thread getTaxisT = new Thread(GetTaxisT);
            //getTaxisT.Start();
            DataTable sdt = _dtDeviceList.Copy();
            gridControl_TaxiList.DataSource = sdt;
            searchLookUpEdit1.Properties.DataSource = sdt;
            gridView1.GroupPanelText = "当前一共" + sdt.Rows.Count + "位员工.";
            //_taxis.Markers.Clear();

        }


        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {

            DataRow dr = this.gridView1.GetFocusedDataRow();//
            if (dr != null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    _drCurrentClickTaxiInfo = dr;
                    popupMenu_MouseLeft.ShowPopup(Control.MousePosition);                  
                }
                else
                {
                    PointLatLng p = new PointLatLng(double.Parse(dr["纬度"].ToString()), double.Parse(dr["经度"].ToString()));
                    MainMap.Position = p;
                }
            }
        }

        

        private void MainMap_OnMarkerClick(GMapMarker item, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (item.Tag == null) return;
                DataTable dt = _dtDeviceList.Copy();
                StringBuilder sb = new StringBuilder();
                sb.Append("手机号码='");
                sb.Append(item.Tag.ToString());
                sb.Append("'");

                DataRow[] drs = dt.Select(sb.ToString());
                _drCurrentClickTaxiInfo = drs.Length >= 1 ? drs[0] : null;
                popupMenu_MouseLeft.ShowPopup(MousePosition);
                
                
            }
        

        }

    


        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            TaxiGPSHistoryForm taxiGpsHistoryForm = new TaxiGPSHistoryForm();
            taxiGpsHistoryForm.ShowDialog();
        }

    

       
        //
        private void barButtonItem12_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_isAlarmSound)
            {
                _isAlarmSound = false;
                btnSoundAlarmicon.Glyph = Resources.sound_off_icon;
                btnSoundAlarmicon.Caption = "打开告警声音";
            }
            else
            {
                _isAlarmSound = true;
                btnSoundAlarmicon.Glyph = Resources.sound_icon;
                btnSoundAlarmicon.Caption = "关闭告警声音";

            }
        }

        

        #region  陈然浩

        public static DataTable DtOverlayList = new DataTable();

        private void GetOverlayInThread()
        {
            while (true)
            {
                DtOverlayList = PositionService.GmapoverlayGetList("").Tables[0];
                if (DtOverlayList.Rows.Count > 0)
                {
                    break;
                }
                Thread.Sleep(10000);
            }
        }

        private void barButtonItem13_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
          
            GmapOverlayManagementForm gmapOverlay = new GmapOverlayManagementForm();
            gmapOverlay.ShowDialog();
            //CallPassengerForm callPsgForm = new CallPassengerForm("13627264054");
            //callPsgForm.ShowDialog();
        }


        //private void DrawOverlayOnMap()
        //{
        //    _overlay.Markers.Clear();
        //    if (barEditItem_showOverlay.EditValue != null &&
        //        barEditItem_showOverlay.EditValue.ToString() == "True")
        //    {
        //        try
        //        {
        //            for (int i = 0; i < DtOverlayList.Rows.Count; i++)
        //            {
        //                AddMarkerToOverlay(DtOverlayList.Rows[i]);
        //            }
        //            _overlay.IsVisibile = true;
        //        }
        //        catch (Exception ex)
        //        {
        //            CommonRoutine.HandlingExceptions(ex);
        //        }
        //    }
        //    else
        //    {
        //        _overlay.IsVisibile = false;
        //    }
        //}

        private void AddMarkerToOverlay(DataRow row)
        {
            if (row == null) return;
            Bitmap obj = GmapOverlayManagementForm.GetMarkerBitmap(row["Overlaytype"].ToString());
            PointLatLng point = new PointLatLng(double.Parse(row["Latitude"].ToString()),
                double.Parse(row["Longitude"].ToString()));
            GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
            {
                ToolTipText = row["OverlayName"].ToString(),
               
            };

            if (barEditItem_showMarkerTip.EditValue != null &&
                barEditItem_showMarkerTip.EditValue.ToString() == "True")
                gMarker.ToolTipMode = MarkerTooltipMode.Always;
            _overlay.Markers.Add(gMarker);
            
        }
        #endregion

       

        private void repositoryItemCheckEdit1_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkEdit = sender as CheckEdit;
            if (checkEdit != null)
            {
                if (checkEdit.Checked)
                {
                    try
                    {
                        _overlay.Markers.Clear();
                        for (int i = 0; i < DtOverlayList.Rows.Count; i++)
                        {
                            AddMarkerToOverlay(DtOverlayList.Rows[i]);
                        }

                        //DtOverlayList.Clear();

                        _overlay.IsVisibile = true;
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                    }
                }
                else
                {
                    _overlay.IsVisibile = false;

                }
            }
        }

       
        private void barButtonItem17_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
            RoleManagementForm roleManagement = new RoleManagementForm();
            roleManagement.ShowDialog();
        }

      

      

        //根据用户所在组设置权限
        private void SetMenuItemsEnableByPermission()
        {
          
            
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.SpecialCarForm + "|"))
            {
                barBtn_DriverForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.ParentForm + "|"))
            {
                barBtnItem_ParentForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" + PowerConfig.GmapOverlayManagementForm + "|"))
            {
                barBtn_GmapOverlayManagementForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" + PowerConfig.CompanyForm + "|"))
            {
                barBtn_CompanyForm.Enabled = true;
            }

            if (MyUserInfo.Permission.Contains("|" + PowerConfig.UserForm + "|"))
            {
                barBtn_UserForm.Enabled = true;
            }


            if (MyUserInfo.Permission.Contains("|" + PowerConfig.RoleManagementForm + "|"))
            {
                barBtnItem_rolemanage.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.GpsForm + "|"))
            {
                barBtn_TaxiGpsHistoryForm.Enabled = true;
            }
            if (MyUserInfo.Permission.Contains("|" + PowerConfig.TeacherUserForm + "|"))
            {
                barBtnItem_TeacherForm.Enabled = true;
            }
                

        }

        //查看当前车辆的历史轨迹
        private void barBtn_TaxiGPSHistoryForm2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_drCurrentClickTaxiInfo != null)
            {
                TaxiGPSHistoryForm gpsHistoryForm = new TaxiGPSHistoryForm(
                    _drCurrentClickTaxiInfo);
                gpsHistoryForm.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("该员工信息以及不存在，请重新刷新列表");
            }
        }

       

        private void barBtn_ChangePassWordForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangePassWordForm changePassWordForm = new ChangePassWordForm();
            changePassWordForm.ShowDialog();
        }

        private void barBtnItem_ParentForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
        }

        private void barBtn_CompanyForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            CompanyForm form = new CompanyForm();
            form.ShowDialog();
        }

        private void barBtnItem_rolemanage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RoleManagementForm role = new RoleManagementForm();
            role.ShowDialog();
        }

        private void barBtnItem_TeacherForm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
        }

       

      

        #region  For Test
        //TaxiInfo tempTaxiInfo = new TaxiInfo();
        //public AutoResetEvent DrawTaxiWait = new AutoResetEvent(false);
        //public AutoResetEvent GetTaxilInListWait = new AutoResetEvent(true);
        //private void DrawAllTaxiInfos()
        //{
        //    System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
        //    myWatch.Start();
        //    List<TaxiInfo> taxiInfoList = PositionService.GetAllTaxiInfos();
        //    foreach (TaxiInfo taxiInfo in taxiInfoList)
        //    {
        //        GetTaxilInListWait.WaitOne();
        //        tempTaxiInfo = taxiInfo;
        //        DrawTaxiWait.Set();
        //    }
        //    myWatch.Stop();
        //    _timerPerf.Stop();
        //    Console.WriteLine("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //    MessageBox.Show("耗时：" + myWatch.ElapsedMilliseconds / 1000f + "s");
        //}



        //AddTaxiMarkers.Clear();
        //foreach (DictionaryEntry dictionaryEntry in TaxiList)
        //{
        //    if (!TaxiMarkersContainKey(dictionaryEntry.Key.ToString()))
        //    {
        //        TaxiInfo temp = (TaxiInfo)dictionaryEntry.Value;
        //        PointLatLng point = new PointLatLng(temp.Latitude, temp.Longitude);
        //        Bitmap obj = GetTaxiBitmap(temp.TaxiState);
        //        ArrayList al = new ArrayList { temp.DriverPhoneNumber, temp.TaxiState };
        //        GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
        //        {
        //            ToolTipText = Convert.ToString(temp.TaxiNo),
        //            ToolTipMode = MarkerTooltipMode.OnMouseOver,
        //            Tag = al
        //        };
        //        AddTaxiMarkers.Add(gMarker);
        //    }
        //}



        //private void DrawAllTaxisOnMap(object sender, EventArgs e)
        //{
        //    //lock (_taxis.Markers)
        //    {
        //        _taxis.Markers.Clear();
        //        _timerPerf.Interval = 10000;
        //        System.Diagnostics.Stopwatch myWatch = new System.Diagnostics.Stopwatch();
        //        myWatch.Start();
        //        List<TaxiInfo> taxiInfoList = PositionService.GetAllTaxiInfos();

        //        foreach (TaxiInfo taxiInfo in taxiInfoList)
        //        {
        //            PointLatLng point = new PointLatLng(taxiInfo.Latitude, taxiInfo.Longitude);
        //            Bitmap obj = GetTaxiBitmap(taxiInfo.TaxiState);
        //            GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
        //            {
        //                ToolTipText = Convert.ToString(taxiInfo.TaxiNo),
        //                ToolTipMode = MarkerTooltipMode.OnMouseOver,
        //                Tag = taxiInfo.DriverPhoneNumber
        //            };
        //            this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Add(gMarker)));
        //        }
        //        myWatch.Stop();
        //        _timerPerf.Stop();
        //        Console.WriteLine("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //        MessageBox.Show("耗时：" + myWatch.ElapsedMilliseconds + "ms");
        //    }
        //}



        //private void timer_Tick(object sender, EventArgs e)
        //{
        //    DrawTaxiWait.WaitOne();
        //    PointLatLng point = new PointLatLng(tempTaxiInfo.Latitude, tempTaxiInfo.Longitude);
        //    Bitmap obj = GetTaxiBitmap(tempTaxiInfo.TaxiState);
        //    GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
        //    {
        //        ToolTipText = Convert.ToString(tempTaxiInfo.TaxiNo),
        //        ToolTipMode = MarkerTooltipMode.OnMouseOver,
        //    };
        //    this.BeginInvoke(new MethodInvoker(() => _taxis.Markers.Add(gMarker)));


        //    GetTaxilInListWait.Set();

        //}

        //private bool TaxiMarkersContainKey(string key)
        //{
        //    lock (_taxis.Markers)
        //    {
        //        return _taxis.Markers.Any(gMapMarker => ((ArrayList)gMapMarker.Tag)[0].ToString() == key);
        //    }
        //}
        #endregion
    }
}